#include "Log.hpp"
#include <vector>
#include "InetAddr.hpp"
#include "Thread.hpp"

using namespace ThreadModlue;
using namespace LogModule;

class Route
{
private:
    bool IsUser(InetAddr &u)
    {
        for (auto &user : _users)
        {
            if (user == u)
            {
                return true;
            }
        }
        return false;
    }

    bool AddUser(InetAddr &user)
    {
        _users.push_back(user);
        LOG(LogLevel::DEBUG) << "新添加了一个用户";
        return true;
    }

    bool DeleteUser(InetAddr& peer)
    {
       for(auto iter = _users.begin() ; iter < _users.end() ;iter++)
       {
            if(*iter == peer)
            {
                _users.erase(iter);
                LOG(LogLevel::DEBUG)<<"删除了一个用户" ;
                return true;
            }
       }
       return false;
    }
public:
    Route()
    {
    }

    void MessageRoute(int sockfd, const std::string& message, InetAddr peer)
    {
        LockGuard lockguard(_mutex);
        if (!IsUser(peer))
        {
            AddUser(peer);
        }

        for (auto &user : _users)
        {
            int send_t = sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&(user.NetAddr()), sizeof(user));
            if (send_t < 0)
            {
                LOG(LogLevel::ERROR) << "发给" << user.GetIP() << " : " << user.GetPort() << "错误";
                continue;
            }
            LOG(LogLevel::DEBUG) << "发给" << user.GetIP() << " : " << user.GetPort() << "成功";
            std::cout << "走到了这66" <<std::endl;

        }

        if (message == "Quit")
        {
            DeleteUser(peer);
            LOG(LogLevel::INFO) << "有一个用户退出";
        }
        return;
    }

    ~Route()
    {
    }

private:
    std::vector<InetAddr> _users;
    Mutex _mutex;
};
